package com.mtzqc.common.livebus

import android.os.SystemClock
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus

inline fun <T, O : Observer<T>> LifecycleOwner.liveBus(
    event: String,
    observer: O
): O {
    LiveEventBus.get<T>(event).observe(this, observer)
    return observer
}

inline fun String.joinLiveBus(key: String?): String {
    return if (key.isNullOrBlank()) this else "${this}_${key}"
}

inline fun <T> String.liveBus(
    owner: LifecycleOwner,
    key: String? = null,
    observer: Observer<T>
): Observer<T> {
    return owner.liveBus(joinLiveBus(key), observer)
}

inline fun <T> String.liveObsBus(
    owner: LifecycleOwner,
    key: String? = null,
    observer: Observer<T>
): BusObserver<T> {
    var event = joinLiveBus(key)
    return owner.liveBus(event, BusObserver(event, observer))
}

fun String.postBus(key: String? = null, any: Any) {
    LiveEventBus.get<Any>(joinLiveBus(key)).post(any)
}

fun String.postTs(key: String? = null) {
    postBus(key, SystemClock.elapsedRealtime())
}
